package problem235;

//235.二叉搜索树的最近公共祖先
//https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-search-tree/

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null) return null;
        if(root == p || root == q) return root;
        if(root.val > p.val && root.val < q.val) return root;
        if(root.val > q.val && root.val < p.val) return root;
        TreeNode res1 = lowestCommonAncestor(root.left, p, q);
        TreeNode res2 = lowestCommonAncestor(root.right, p, q);
        if(res1 != null) return res1;
        return res2;
    }
}